import Storage from 'react-native-storage';
var FileTransfer = require('@remobile/react-native-file-transfer');
var TimerMixin = require('react-timer-mixin');
var storage = new Storage({
  // maximum capacity, default 1000
  size: 1000,
  // expire time, default 1 day(1000 * 3600 * 24 secs)
  defaultExpires: 1000 * 3600 * 24,
  // cache data in the memory. default is true.
  enableCache: true,
  // if data was not found in storage or expired,
  // the corresponding sync method will be invoked and return
  // the latest data.
  sync : {
    // we'll talk about the details later.
  }
})

 function DownloadCenter(){
    // global.storage = storage;
    var uploadList  = [], //上传列表
    downloadList = [], //下载列表
    uploadFinishData = [],
    downloadFinishData = [],
    uploadDbDatas = [],
    downloadDbDatas = [],
    uploadMergeDatas =[],
    downloadMergeDatas = [],
    willDelDatas =[];


    function download(files) {
      var dLength = downloadList.length
      for (var i = 0; i < files.length; i++) {
        downloadList.push(files[i]);
      }
      for (var i = dLength; i < downloadList.length; i++) {
        if(downloadList){
          apiDownload(downloadList[i])
        }
      }
    }
    function upload(files){
      var uLength = uploadList.length
      for (var i = 0; i < files.length; i++) {
        uploadList.push(files[i])
      }
      for (var i = uLength; i < uploadList.length; i++) {
        if(uploadList){
          apiUpload(uploadList[i])
        }
      }
    }

    function getCurDataList(isupload){
      return isupload?uploadList:downloadList;
    }

    function apiUpload(file){
      var filename = file.title;
      var options = {
          fileKey: 'file',
          fileName: filename,
          chunkedMode: false,
          mimeType: file.mimeType,
          headers: {
            'Content-Type': 'multipart/form-data',
            'Connection': 'close',
            'Authorization': 'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE=',
            'Override': true
          }
      }

      var server = 'http://42.159.143.17:6080/alfresco/webdav/User Homes/tw.feng@haihangyun.com/'+filename;
      var filePath = file.filePath;
      var fileTransfer = new FileTransfer();
      file.progress = 0;
      fileTransfer.onprogress = (progress) => {
        file.progress = parseInt((progress.loaded/progress.total)*100)
        console.log('进度',file.progress);
        if(file.progress==100){
          uploadFinishData.push(file)
          for (var j = 0; j < uploadList.length; j++) {
            if(uploadList[j].name == file.name){
              uploadList.splice(j,1);
            }
          }
        }
      }
      fileTransfer.upload(filePath,encodeURI(server),(result)=>{
          console.log('上传成功',result);
          saveData(file,'upload','1001');
      }, (error)=>{
          console.log('上传失败',error);
      }, options);
    }
    function apiDownload(file){
        var uri = encodeURI("http://42.159.143.17:6080/alfresco/webdav"+file.webdavpath+"?alf_ticket=TICKET_b78ac994782dbd1b71a9385c8a78edad5fa04550");
        var options = {
            headers: {
              'Connection': 'close',
              'Authorization': 'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE=',
              'Override': 'true'
            }
        };
        var fileTransfer = new FileTransfer();
        file.progress = 0;
        fileTransfer.onprogress = (progress) => {
          file.progress = parseInt((progress.loaded/progress.total)*100);
          if(file.progress==100){
            downloadFinishData.push(file)
            for (var j = 0; j < downloadList.length; j++) {
              if(downloadList[j].name == file.name){
                downloadList.splice(j,1)
              }
            }
          }
        }
        fileTransfer.download(
            uri,
            'sdcard/RNdata/'+file.name,
            function(result) {
              console.log('下载成功');
              saveData(file,'download','1002');
            },
            function(error) {
              console.log('下载出错...',error);
            },
            true,
            options
        );
      }


    function saveData(file,type,id){
        getData(type,id)
        .then( ret => {
          var files = [];
          files = ret;
          files.push(file);
          save(files,type,id);//files,file
      }).catch( err => {
        var files =[];
        files.push(file)
        save(files,type,id);
      });

    }
    function save(files,type,id) {//files = [],file

      for (var i = 0; i < files.length; i++) {
        files[i].progress=100
      }
      // file.progress = 100;
      storage.save({
      key: type,
      // id:file.id,
      rawData:files,
      expires:null
      });

    }

    function getData(type,id){
      return storage.load({
        key: type
        // id:id
        });
    }

    function getDbDatas() {
      getData('download','1002')
      .then(ret => {
        for (var i = 0; i < ret.length; i++) {
          downloadDbDatas.push(ret[i])
        }
      })
      .catch(err => {console.log('读取数据库数据失败！！')});
      getData('upload','1001')
      .then(ret => {
        for (var i = 0; i < ret.length; i++) {
          uploadDbDatas.push(ret[i])
        }
      })
      .catch(err => {console.log('读取数据库数据失败！！')});
    }

    function getMergeData(flag){ //true 为上传 false为下载
      if (flag) {
        for (var i = 0; i < uploadList.length; i++) {
          uploadMergeDatas.push(uploadList[i])
        }
        for (var j = 0; j < uploadFinishData.length; j++) {
          uploadMergeDatas.push(uploadFinishData[j])
        }
        for (var k = 0; k < uploadDbDatas.length; k++) {
          uploadMergeDatas.push(uploadDbDatas[k])
        }
        return uploadMergeDatas;
      } else {
        for (var l = 0; l < downloadList.length; l++) {
          downloadMergeDatas.push(downloadList[l])
        }
        for (var m = 0; m < downloadFinishData.length; m++) {
          downloadMergeDatas.push(downloadFinishData[m])
        }
        for (var n = 0; n < downloadDbDatas.length; n++) {
          downloadMergeDatas.push(downloadDbDatas[n])
        }
        return downloadMergeDatas;
      }
    }
    function clearMergeData(aflag){//true 为上传 false为下载
      if(aflag){
        uploadMergeDatas.length = 0;
      }else{
        downloadMergeDatas.length = 0;
      }
    }

    function delFile(files){
      willDelDatas = files;
      for (var i = 0; i < files.length; i++) {
        var url = 'http://42.159.143.17:6080/alfresco/service/slingshot/doclib/action/file/node/workspace/SpacesStore/'+files[i].id;
        fetch(url,{
           method: 'DELETE',
           headers:{
             'Connection': 'close',
             'Authorization': 'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE=',
             'Override': 'true'
           }
        })

      }

    }

    return {
      getDbDatas, //在下载中心首先获取数据库的数据
      download,  // 下载接口
      upload, //上传接口
      getMergeData, //得到合成的数据
      clearMergeData, //清除合成的数据
      getCurDataList,  //返回当前正在下载的数据列表
      delFile         //删除文件
    }
}
module.exports = DownloadCenter;
